package com.hotel.project.gateway.config;

import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关统一异常
 *
 * @author: peng.ni
 * @date: 2022/04/13
 */
public class AbstractExceptionHandler {
    private static final String DEFAULT_ERROR_CODE = "30199";
    private static final String DEFAULT_ERROR_MSG = "服务器内部出错啦~";
    public static final String NOT_FOUND_MSG = "请求服务迷路了";


    protected String formatMessage(Throwable ex) {
        String errorMessage;
        if (ex instanceof NotFoundException) {
            // 接口路径404
            errorMessage = NOT_FOUND_MSG;
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            errorMessage = responseStatusException.getMessage();
        } else {
            errorMessage = ex.getMessage();
        }
        return errorMessage;
    }

    protected Map<String, Object> buildErrorMap(String errorMessage) {
        Map<String, Object> resMap = new HashMap<>(2);
        resMap.put("errno", DEFAULT_ERROR_CODE);
        resMap.put("errmsg", errorMessage);
        resMap.put("data", new Object());
        return resMap;
    }
}
